import { Inject, Provide } from '@midwayjs/decorator';
import { Context } from '@midwayjs/koa';
import { InjectEntityModel } from '@midwayjs/orm';
import { createHash } from 'crypto';
import { Repository } from 'typeorm';
import { User } from '../entity/User';

@Provide()
export class UserService {
  @Inject()
  ctx: Context;

  @InjectEntityModel(User)
  userModel: Repository<User>;

  async login({ username, password }): Promise<User> {
    const user = await this.userModel.findOne(
      {
        username,
      },
      {
        select: ['id', 'salt', 'password'],
      }
    );
    const md5 = createHash('md5');
    const _password = md5.update(`${password}:${user.salt}`).digest('hex');
    if (user.password !== _password) {
      this.ctx.throw(400, '用户名或密码错误');
    }
    return this.userModel.findOne(user.id);
  }
}
